from fastapi import APIRouter, Query
from tortoise.expressions import Q
from app.controllers.goods.category import category_controller
from app.schemas.base import Success, SuccessExtra,Fail

mini_goods_category_router = APIRouter()


@mini_goods_category_router.get("/list", summary="查看分类列表")
async def list_category(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description="分类名称"),
        parent_id: int = Query(0, description="上级id"),
):
    q = Q()
    if name:
        q &= Q(name__contains=name)
    if parent_id:
        q &= Q(parent_id=parent_id)
    total, data = await category_controller.list_category(page=page, page_size=page_size, search=q)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@mini_goods_category_router.get("/tree", summary="树形分类")
async def tree_dept():
    data = await category_controller.get_tree()
    datas = [{
        "id": 0,
        "name": "全部",
        "desc": "全部",
        "order": 1,
        "parent_id": -1,
        "children": data,  # 递归构建子部门
    }]
    return SuccessExtra(data=datas)
